import gnu.io.SerialPortEvent;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import util.SqlUtils;


import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 串口调试助手
 */
public class SerialAssistant {
    @FXML
    private TextArea receiveText; // 接收区
    @FXML
    private TextArea sendText; // 发送区
    @FXML
    private Button openBnt; // 打开按钮
    @FXML
    private ComboBox<String> comboBox; // 串口号
    @FXML
    private ComboBox<Integer> BaudRateBox; // 波特率

    private SerialController serialController;
    private List<String> systemPorts; // 串口号
    private boolean isOpen = false; // 串口是否打开

    public SerialAssistant() {
        serialController = new SerialController();
    }

    /**
     * 点击commbox，刷新里面的数据
     */
    public void onShowComboBox(Event event) {
        systemPorts = SerialController.getSystemPort();
        comboBox.getItems().clear();
        comboBox.getItems().addAll(systemPorts);
    }

    /**
     * 点击BaudRateBox,显示可供选择的波特率
     */
    public void onShowBaudRateBox(Event event) {
        BaudRateBox.getItems().addAll(2400, 4800, 9600, 19200, 38400, 57600, 115200);
        BaudRateBox.setVisibleRowCount(4);
    }

    /**
     * 打开串口
     */
    public void onActionOpenBtn(ActionEvent actionEvent) {
        isOpen = !isOpen;
        if (isOpen) {
            if (!serialController.open(comboBox.getValue(), BaudRateBox.getValue())) {
                return;
            }
            serialController.setListenerToSerialPort(ev -> {
                if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                    String str = null;
                    System.out.println("====================================================================================");
                    try {

                        str = serialController.readData();

                        //正则表达式将数字分割出来
                        String regEX="[^0-9]";
                        Pattern compile = Pattern.compile(regEX);

                        Matcher matcher = compile.matcher(str);

                        String guangzhao = matcher.replaceAll("").trim();

                        System.out.println("guangzhao:"+guangzhao);

                        //数据库连接
                        Connection connection = SqlUtils.getConnection();

                        Statement statement = connection.createStatement();

                        /**
                         * ID GROUPID XH VALUE UPDATETIME
                         */
                        //String sql = "SELECT * FROM WSNTEST";
//                        String sql1 = "INSERT INTO WSNTEST(GROUPID,XH,VALUE) VALUES ('202004071-202003978-202003983','wenglushi','"+"温度:"+wd+"湿度:"+sd+"')";

//                        String sql2 = "INSERT INTO WSNTEST(GROUPID,XH,VALUE) VALUES ('202004071-202003978-202003983','wenglushi','"+"光照:"+guangzhao+"')";

//                        if (wd < 30 && wd>10){
//                            statement.executeUpdate(sql1);
//                        }
//                        if(Integer.parseInt(guangzhao) > 100){
//                            statement.executeUpdate(sql2);
//                        }



                        if (guangzhao.length()==8){//温湿度
                            char c0 = guangzhao.charAt(0);
                            char c1 = guangzhao.charAt(1);
                            char c2 = guangzhao.charAt(2);
                            char c3 = guangzhao.charAt(3);
                            char c4 = guangzhao.charAt(4);
                            char c5 = guangzhao.charAt(5);
                            char c6 = guangzhao.charAt(6);
                            char c7 = guangzhao.charAt(7);

                            String wsd="湿度："+c0+c1+"."+c2+c3+" 温度："+c4+c5+"."+c6+c7;
                            String sql1 = "INSERT INTO WSNTEST(GROUPID,XH,VALUE) VALUES ('20200471-202003978-202003983','wenglushi','"+wsd+"')";

                            statement.executeUpdate(sql1);
                        }else if(guangzhao.length()==3){
                            String gzhao = "光照："+guangzhao;

                            String sql2 = "INSERT INTO WSNTEST(GROUPID,XH,VALUE) VALUES ('20200471-202003978-202003983','wenglushi','"+gzhao+"')";
                            statement.executeUpdate(sql2);
                        }
//=======================================================================================================================================
                        System.out.println("str:"+str);

//                        byte[] bytes = Hex.decodeHex(str);

//                        System.out.println(bytes);

                        char[] chars = str.toCharArray();

                        ArrayList<String> strings = new ArrayList<>();

                        System.out.println("strings:"+strings);

                        for (int i= 0;i<chars.length;i++){
                            String s = Integer.toHexString(chars[i]);

                            strings.add(s);

                            System.out.println("000000000:"+s);
                        }

                        System.out.println("1111111:"+strings);

                        Integer wd = Integer.parseInt(strings.get(1),16);


//                        Integer gz = Integer.parseInt(((Integer.parseInt(strings.get(1),16)*256)+Integer.parseInt(strings.get(2),16))/10+"");
//                        Integer gz = Integer.parseInt(((Integer.parseInt(strings.get(1)+strings.get(2),16)))+"");

                        System.out.println("gz:"+guangzhao);

                        Integer sd = Integer.parseInt(strings.get(2),16);


                        System.out.println("2222222:"+"wd:"+wd+"sd:"+sd);


//                        ResultSet resultSet = statement.executeQuery(sql);

/*
                        while (resultSet.next()) {
                            String ID = resultSet.getString("ID");
                            String GROUPID = resultSet.getString("GROUPID");
                            String XH = resultSet.getString("XH");
                            String VALUE = resultSet.getString("VALUE");
                            String UPDATETIME = resultSet.getString("UPDATETIME");

                            System.out.println(ID+GROUPID+XH+VALUE+UPDATETIME);
                        }*/



                    } catch (UnsupportedEncodingException | SQLException e) {
                        e.printStackTrace();
                    }
                    String finalStr = str;
                    Platform.runLater(() -> {
                        if (receiveText.getLength() < 4000) {
                            receiveText.appendText(finalStr);
                        } else {
                            receiveText.deleteText(0, finalStr.length());
                            receiveText.appendText(finalStr);
                        }
                    });

                }
            });
            openBnt.setText("关闭串口");
        } else {
            serialController.close();
            openBnt.setText("打开串口");
        }
    }

    /**
     * 发送数据
     */
    public void onActionSendBtn(ActionEvent actionEvent) {
        serialController.sendData(sendText.getText());
    }

    /**
     * 清除接收框
     */
    public void clear(ActionEvent actionEvent) {
        receiveText.clear();
    }
}

